import { prisma } from '../../utils/prisma'
import { assertChildOwnership } from '../../utils/guard'
import { getWeekRangeMonday } from '../../utils/date'
import { z } from 'zod'

export default eventHandler(async (event) => {
  const q = getQuery(event)
  const schema = z.object({ childId: z.string(), weekStart: z.string() })
  const parsed = schema.safeParse(q)
  if (!parsed.success) throw createError({ statusCode: 422, statusMessage: 'INVALID_INPUT' })
  const childId = Number(parsed.data.childId)
  if (!Number.isFinite(childId)) throw createError({ statusCode: 400, statusMessage: 'BAD_ID' })
  await assertChildOwnership(event, childId)
  const { start, end } = getWeekRangeMonday(parsed.data.weekStart)

  const ledger = await prisma.pointsLedger.findMany({
    where: {
      childId,
      occurredAt: { gte: start, lte: end }
    },
    orderBy: { occurredAt: 'asc' }
  })
  const days = Array.from({ length: 7 }, () => 0)
  for (const l of ledger) {
    const idx = Math.floor((l.occurredAt.getTime() - start.getTime()) / (24 * 60 * 60 * 1000))
    if (idx >= 0 && idx < 7) {
      const v = l.kind === 'earn' ? l.amount : l.kind === 'spend' ? -l.amount : l.amount
      days[idx] += v
    }
  }
  const total = days.reduce((s, x) => s + x, 0)
  return { days, total, range: { start, end } }
})


